#include "qmlfile.h"

#include <QtDeclarative/qdeclarative.h>
#include <QDir>
#include <QFileDialog>

QMLFile::QMLFile(QDeclarativeItem *parent):
    QDeclarativeItem(parent)
{
    // By default, QDeclarativeItem does not draw anything. If you subclass
    // QDeclarativeItem to create a visual item, you will need to uncomment the
    // following line:
    
    // setFlag(ItemHasNoContents, false);

    m_operationState = Idle;
    _pfile = NULL;

    connect(&_fileAcync, SIGNAL(finished(bool)), this, SLOT(asyncFinished(bool)));
}

QMLFile::~QMLFile()
{
}

//存在確認
bool QMLFile::exists(const QString &path)
{
    return QFile::exists(path);
}

//ディレクトリ内のディレクトリリスト
QStringList QMLFile::getEntryList(const QString &path)
{
    QStringList list;
    return getEntryList(path, Dirs, list);
}

QStringList QMLFile::getEntryList(const QString &path, const EntryType type, const QStringList &nameFilters)
{
    QStringList ret;
    QDir dir(path);
    if(type == Dirs){
        dir.setFilter(QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot);
        if(nameFilters.length() > 0){
            dir.setNameFilters(nameFilters);
        }
    }else{
        dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
        dir.setNameFilters(nameFilters);
    }
    dir.setSorting(QDir::Name);// | QDir::Reversed);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        ret.append(fileInfo.fileName());
    }
    return ret;
}

//フォルダ選択ダイアログ
QString QMLFile::getExistingDirectory(const QString &title, const QString &default_path)
{
    return QFileDialog::getExistingDirectory(NULL, title,
                                             default_path,
                                            QFileDialog::ShowDirsOnly
                                            | QFileDialog::DontResolveSymlinks);
}
//ファイル選択ダイアログ
QString QMLFile::getOpenFileName(const QString &title, const QString &default_path, const QString &filter)
{
    return QFileDialog::getOpenFileName(NULL, title
                                        , default_path
                                        , filter);
}


//ファイルコピー開始
bool QMLFile::copy(const QString &fileName, const QString &newName)
{
    bool ret = false;
    if(m_operationState != Idle){
    }else if(fileName.length() < 1 || newName.length() < 1){
    }else{
        _fileAcync.m_fileName = fileName;
        _fileAcync.m_newName = newName;
        _fileAcync.start();
        ret = true;
    }
    return ret;
}

//カレントパスを取得
QString QMLFile::currentPath()
{
    return QDir::currentPath();
}
//カレントパスを設定
bool QMLFile::setCurrent(const QString &path)
{
    return QDir::setCurrent(path);
}
//ファイル名取得
QString QMLFile::fileName(const QString &path)
{
    QFileInfo fi(path);
    return fi.fileName();
}
//パス取得
QString QMLFile::filePath(const QString &path)
{
    QFileInfo fi(path);
    return fi.path();
}
//ファイル名（拡張子なし）を取得
QString QMLFile::fileBaseName(const QString &path)
{
    QFileInfo fi(path);
    return fi.completeBaseName();
}
//拡張子を取得
QString QMLFile::fileSuffix(const QString &path)
{
    QFileInfo fi(path);
    return fi.completeSuffix();
}

/////////////////////////////////////////////////////////////
// ファイル操作
/////////////////////////////////////////////////////////////

QStringList QMLFile::readTextFile(const QString &fileName)
{
    QStringList list;
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
    }else{
        QTextStream in(&file);
        while(!in.atEnd()){
            list.append(in.readLine());
        }
        file.close();
    }
    return list;
}
#if 0
bool QMLFile::openFile(const QString &fileName)
{
    bool ret = false;
    QString full_path = fileName;
    QFileInfo fileInfo(fileName);
    QString old_current;

//    closeFile();
#if defined(Q_OS_WIN)
    full_path.replace("\\", "/");
#endif
    qDebug() << "QMLFile::openFile " << full_path
             << "," << fileInfo.absolutePath()
             << "," << fileInfo.fileName();


    //カレント移動
    old_current = QDir::currentPath();
    QDir::setCurrent(fileInfo.absolutePath());
    qDebug() << "   setCurrent:" << fileInfo.absolutePath();

//    _file.setFileName(fileInfo.fileName());
//    qDebug() << "   setFileName";
//    if(!_file.open(QIODevice::ReadOnly | QIODevice::Text)){
//        qDebug() << "   open fail";
//    }else{
//        qDebug() << "   open success";
//        _textStream.setDevice(&_file);
//        qDebug() << "   setDevice";
//        ret = true;
//    }

    closeFile();

//    _pfile = new QFile(fileInfo.fileName());
//    if(!_pfile->open(QIODevice::ReadOnly | QIODevice::Text)){
//        qDebug() << "   open fail";
//    }else{
//        qDebug() << "   open success";
//    }

    //カレントを戻す
    QDir::setCurrent(old_current);

    return ret;
}

void QMLFile::closeFile()
{
    qDebug() << "QMLFile::closeFile";

    qDebug() << "_pfile:" << (_pfile == NULL ? "NULL" : "not NULL");

    if(_pfile != NULL){
        qDebug() << "   not null";
        if(_pfile->isOpen()){
            qDebug() << "   is open";
//            _pfile->close();
        }
        delete _pfile;
    }
}

bool QMLFile::atEnd()
{
    qDebug() << "QMLFile::atEnd";

    if(_file.isOpen()){
        return _textStream.atEnd();
    }else{
        return false;
    }
}

QString QMLFile::readLine()
{
    qDebug() << "QMLFile::readLine";

    QString line = "";
    if(!_file.isOpen()){
    }else if(_textStream.atEnd()){
    }else{
        line = _textStream.readLine();
    }
    return line;
}
#endif

/////////////////////////////////////////////////////////////
// setter/getter
/////////////////////////////////////////////////////////////


//コピーなどの状態ステータス
QMLFile::OperationStateType QMLFile::operationState() const
{
    return m_operationState;
}
void QMLFile::setOperationState(const OperationStateType &state)
{
    if(state != m_operationState){
        m_operationState = state;
        emit operationStateChanged();
    }
}

//非同期処理の応答スロット
void QMLFile::asyncFinished(bool result)
{
    m_operationState = result ? FinishedSuccess : FinishedFail;
    emit operationStateChanged();
    m_operationState = Idle;
}
